import re

from django.conf import settings
from django.contrib.auth import login, authenticate, logout
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.views.generic import View
from django.http import HttpResponse

from cart.utils import megre_cart
from user.models import User
from user.serialzier import UserSerialzier
from celery_tasks.tasks import send_register_active_email
from itsdangerous import TimedJSONWebSignatureSerializer
from user.models import Address
from django_redis import get_redis_connection
from goods.models import GoodsSKU
from order.models import OrderInfo


class LoginView(View):

    def get(self, request):
        # 登录页渲染
        if request.user.is_authenticated():
            return redirect('/')
        return render(request, 'login.html')

    def post(self, request):
        """
            登录
        """
        # 获取数据
        data = request.POST
        username = data.get('username')
        pwd = data.get('pwd')

        # # 查询用户
        # try:
        #     user = User.objects.get(username=username)
        # except:
        #     return render(request, 'login.html', {'errmsg': "用户不存在"})
        # # 校验密码
        # if not user.check_password(pwd):
        #     return render(request, 'login.html', {'errmsg': "错误"})
        # 用户验证方法可以配合login方法使用
        user = authenticate(request=request, username=username, password=pwd)
        if user is None:
            return render(request, 'login.html', {'errmsg': "用户名或密码错误"})
        if not user.email_active:
            return render(request, 'login.html', {'errmsg': "邮箱未验证"})

        # 状态保持
        login(request, user)
        # request.session['username'] = user.username

        # return render(request, 'index.html', {'user': user})
        # 获取不到next给一个默认值'/'
        next = request.GET.get('next', '/')

        # 合并购物车
        response = redirect(next)
        response = megre_cart(request, response, user)
        return response


class RegiseterView(View):

    def get(self, request):
        # 注册页渲染
        return render(request, 'register.html')

    def post(self, request):
        # 跳转到登录进行登录
        # username = request.POST.get('user_name')
        # password = request.POST.get('pwd')
        # password2 = request.POST.get('cpwd')
        # email = request.POST.get('email')
        # allow = request.POST.get('allow')
        #
        # if not all([username, password, password2, email, allow]):
        #     return render(request, 'register.html', {'errmsg': '缺失参数'})
        # if password2 != password:
        #     return render(request, 'register.html', {'errmsg': '密码不一致'})
        # if allow != 'on':
        #     return render(request, 'register.html', {'errmsg': '未同意协议'})
        # try:
        #     user = User.objects.create_user(username=username, password=password, email=email)
        # except:
        #     return render(request, 'register.html', {'errmsg': '保存失败'})

        data = request.POST.dict()
        del data['csrfmiddlewaretoken']
        ser = UserSerialzier(data=data)
        try:
            ser.is_valid(raise_exception=True)
        except Exception as e:
            print(e)
            return render(request, 'register.html', {'errmsg': '验证失败'})
        ser.save()

        # 发送邮件
        # 使用异步任务
        # 用户的信息加密方便进行验证
        tjs = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        token = tjs.dumps({'username': data['username'], 'email': data['email']}).decode()
        send_register_active_email.delay(data['email'], data['username'], '?token=' + token)

        return redirect('/user/login')
        # return render(request,'register.html')


class ActiveView(View):

    def get(self, request):

        # 获取验证的的加密信息
        token = request.GET.get('token')
        tjs = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return render(request, 'register.html', {'errmsg': '验证失败'})
        username = data.get('username')
        email = data.get('email')
        try:
            user = User.objects.get(username=username, email=email)
        except:
            return render(request, 'register.html', {'errmsg': '验证失败'})
        # 更新邮箱状态
        user.email_active = True
        user.save()
        # 返回到登录页
        return redirect('/user/login')


class LogOutView(View):

    def get(self, request):
        logout(request)
        return redirect('/')


class UserInfoView(View):

    def get(self, request):
        # 渲染用户中心页面
        # if request.user.is_authenticated():
        #     return render(request, 'user_center_info.html')
        # else:
        #     return redirect('/user/login')
        # 查询默认地址
        user = request.user
        try:
            address = user.address_set.get(is_default=True)
        except:
            address = None

        # 查询浏览历史记录
        # 1、获取用户id ，在reids是以用户id作为key
        id = request.user.id
        # 2、连接redis
        conn = get_redis_connection('history')
        # 3、获取用户的浏览商品id,列表获取数据
        sku_ids = conn.lrange('history_%d' % id, 0, 10)
        # 4、根据商品id查询sku表获取商品数据对象 范围查询 in ，在sku_ids商品都会进行查询
        skus = GoodsSKU.objects.filter(id__in=sku_ids)
        return render(request, 'user_center_info.html', {'address': address, 'goods_li': skus})


class UserAddressView(View):

    def get(self, request):
        # 渲染地址页面
        # 获取当前的用户的地址信息
        user = request.user
        addresses = user.address_set.all()
        # try:
        #     address = user.address_set.get(is_default=True)
        # except:
        #     address = None
        # return render(request, 'user_center_site.html', {'address': address})

        return render(request, 'user_center_site.html', {'addresses': addresses})

    def post(self, request):
        # 1、获取数据
        data = request.POST
        receiver = data.get('receiver')
        addr = data.get('addr')
        zip_code = data.get('zip_code')
        phone = data.get('phone')
        user = request.user
        # 2、验证数据
        if not re.match(r'1[3-9]\d{9}', phone):
            return render(request, 'user_center_site.html', {'errmsg': '手机格式不正确'})
        # 3、保存地址
        address = Address.objects.create(user=user, receiver=receiver, addr=addr, zip_code=zip_code, phone=phone)
        # 判断是否有默认地址
        count = Address.objects.filter(is_default=True, user=user).count()
        if count == 0:
            # 将新保存的数据作为默认值
            address.is_default = True
            address.save()

        # 4、数据渲染
        # return render(request, 'user_center_site.html', {'address': address})
        # 多个地址信息渲染
        # addresses = []
        # addresses.append(address)
        # return render(request, 'user_center_site.html', {'addresses': addresses})
        return redirect('/user/address')


class UserOrderView(View):

    def get(self, request, num_page):
        # 获取用户
        user = request.user
        # 根据用户查询用的所有订单
        orders = OrderInfo.objects.filter(user=user)
        # 订单数据分页
        paginator = Paginator(orders, 2)
        try:
            order_page = paginator.page(num_page)
        except:
            return render(request, 'user_center_order.html')

        for order in order_page:
            # 获取订单的商品信息
            order.order_skus = order.ordergoods_set.all()
            order.status_name = 'aaaa'
            for order_sku in order.order_skus:
                order_sku.amount = order_sku.count * order_sku.price

        context = {
            'order_page':order_page,
            'pages': paginator.page_range
        }

        return render(request, 'user_center_order.html',context)
